#coding:utf-8
from Tkinter import *
import os
from PIL import Image
from PIL import ImageTk

import win32clipboard
import win32gui
import win32api
import win32con
import traceback
from cStringIO import StringIO


class CanvasImg():
    def __init__(self, root, path):
        self.root = root
        self.imgob = Image.open(path)
        self.size = self.imgob.size
        self.PhotoImage = ImageTk.PhotoImage(file=path)

    def addImg(self, row, column):
        canv = Canvas(self.root, bg='white', width=self.size[0], height=self.size[1])
        canv.bind("<Button-1>", self.addFunctionClick)
        canv.create_image((self.size[0] / 2, self.size[1] / 2), image=self.PhotoImage)
        canv.grid(row=row, column=column, columnspan=1, sticky=W + E + N + S, padx=1, pady=1)
        self.root.update_idletasks()

    def addFunctionClick(self, event):
        print 'u click'
        output = StringIO()
        self.imgob.convert("RGB").save(output, "BMP")
        data = output.getvalue()[14:]
        output.close()
        win32clipboard.OpenClipboard()
        try:
            # Unicode tests
            win32clipboard.EmptyClipboard()
            win32clipboard.SetClipboardData(win32con.CF_DIB, data)
        except:
            traceback.print_exc()
        finally:
            win32clipboard.CloseClipboard()

def ShowSearchUi(root):
    e = StringVar()
    e.set('happy')
    entry = Entry(root, textvariable = e)
    entry.grid(row=0, column=0, sticky=W + E + N + S, padx=10, pady=10)
    findbtn = Button(root, text='Search', relief=GROOVE, command = lambda :searchEmotion(entry,frame,e))
    frame = Frame(root)
    frame.grid(row=1, column=0, columnspan=8, sticky=W + E + N + S, padx=5, pady=5)
    findbtn.grid(row=0, column=1, sticky=W + E + N + S, padx=10, pady=10)

def searchEmotion(entry,frame,e):
    keyword = entry.get()
    if not os.path.exists(keyword):
        print u'不存在目录!!'
        exit()
    e = ''
    showAllEmotion(frame, keyword)

def showAllEmotion(frame, keyword):
    row = 0
    column = 0
    inst = {}
    imgs = os.listdir(keyword)
    for i in imgs:
        inst[i] = CanvasImg(frame, os.path.join(keyword, i))
        inst[i].addImg(row,column)
        #frame.update_idletasks()
        column += 1
        if(column == 8):
            row += 1
            column = 0
    #root.mainloop()



if __name__ == '__main__':
    root = Tk()
    ShowSearchUi(root)
    root.mainloop()